<template>
  <el-form ref="form" :model="food" label-width="80px">
    <el-form-item label="食物名称">
      <el-input v-model="food.name" placeholder="请输入食物名称"></el-input>
    </el-form-item>
    <el-form-item label="食物类型">
      <el-select v-model="food.type" placeholder="请选择食物类型">
        <el-option label="蔬菜" value=0></el-option>
        <el-option label="水果" value=1></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="食物的量">
      <el-switch v-model="food.sel" active-text="数量" inactive-text="质量"></el-switch>
    </el-form-item>
    <el-form-item label="食物数量(个)">
      <el-slider v-model="food.quantity" :disabled="changeState" :max="100"></el-slider>
    </el-form-item>
    <el-form-item label="食物质量(克)">
      <el-slider v-model="food.weight" :disabled="!changeState" :max="1000"></el-slider>
    </el-form-item>
    <el-form-item label="保存时间(天)">
      <el-input-number v-model="food.time" :min="1" :max="10" label="描述文字"></el-input-number>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">添加食物</el-button>
      <el-button @click="goBack">返回</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  const axios = require('axios')
  import {
    ElMessage
  } from 'element-plus'
  export default {
    data() {
      return {
        food: {
          name: '',
          type: 0,
          sel: true,
          quantity: 1,
          weight: 200,
          time: 3
        }
      }
    },
    methods: {
      onSubmit() {
        // 处理食物数量和质量
        if (this.food.sel === true) {
          this.food.quantity = 0
        } else {
          this.food.weight = 0
        }
        console.log('submit!');
        console.log(this.food);
        const path = 'http://10.189.205.246:5000/insertFood'
        let postData = {
          "food": this.food
        }
        axios
          .post(path, postData, {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then((res) => {
            console.log(res)
            if (res.data === "success") {
              ElMessage({
                message: "添加" + this.food.name + "成功",
                type: 'success',
              })
            } else {
              ElMessage.error("添加" + this.food.name + "失败")
            }
            this.getFoods();

          })
          .catch(error => {
            console.log(error);
          });
      },
      goBack() {
        this.$router.go(-1);
      }
    },
    computed: {
      changeState() {
        return this.food.sel
      }
    }
    // watch(food.sel,
    //   (old, new) = {
    //     console.log("监听触发", old, new)
    //     this.isdisplay = new
    //   })
  }
</script>

<style lang="scss" scoped></style>
